

/**
 * redirects to given url
 * @param 		string		url
 */
function redirect(url) {
	document.location.href = url;
}


/**
 * checks if the id is a jquery valid id
 * if not, add '#' at the first position
 * @param 		string		id
 * @returns		string
 */
function getJqueryId(id){
	if (id != null && isNaN(id) && id.length > 0){
		if (id[0] != '#')
			id = '#' + id;
	}
	return id;
}


/**
 * removes all error classes. if an error occurs, mark all fields as errorElement
 * @param response
 * @param prefix
 */
function interpretResponse(response, prefix){
	prefix = getJqueryId(prefix);
	$(prefix + 'FORM .errorElement').removeClass('errorElement');
	if (response != null){
		if (response.STATUS != null && response.STATUS == pageSettings.failed){	
			if (response.FIELDS != null)
				markErrorFields(response.FIELDS);
			if (response.MESSAGES != null)
				addMessages(response.MESSAGES);
		} else if (response.STATUS == pageSettings.success){
			$(prefix + 'SUCCESS').show(400, function(){
				setTimeout(function() {
					$(prefix + 'SUCCESS').hide(400);
				}, 2000);
			});
		}
	}
}


/**
 * sets the error status to all given fields
 * @param 		array		fields
 */
function markErrorFields(fields){
	for(var field in fields){
		var fieldName = fields[field];
		$('#' + fieldName).addClass('errorElement');
	}
}


/**
 * add message entries to the error dialog box
 * @param messages
 */
function addMessages(messages){
	var errorList = '<ul style="padding-left: 20px">';
	for(var message in messages)
		errorList += '<li>' + messages[message] + '</li>';
	errorList += '</ul>';
	showMessage(errorList);
}


/**
 * shows an dialog window
 * @param message
 */
function showMessage(message){
	var id = "modalDialog_" + getUniqueId();
	var output = '<div id="' + id + '" style="height: 200px; width: 300px; padding:10px">' + message + '</div>';
	id = '#' + id;
	$(id).remove();
	$('body').append(output);
	$(id).dialog({
		title: 'Achtung',
		modal: true,
		buttons: [{
			text: 'Ok',
			iconCls: 'icon-ok',
			handler: function(){
				$(id).dialog('close');
			}
		}]
	});
}


/**
 * generates a custom dialog
 * @param 		string		content
 * @param 		mixed		buttonsArr
 * @param 		int			height
 * @param 		int			width
 * @param 		string		header
 * @param 		string		id		id of dialog
 */
function showCustomDialog(content, buttonsArr, height, width, header, id, callback){
	var output = '<div id="' + id + '" style="height: ' + height + 'px; width: ' + width + 'px; padding:10px">' + content + '</div>';
	id = getJqueryId(id);
	$(id).remove();
	$('body').append(output);
	$(id).dialog({
		title: header,
		modal: true,
		buttons: buttonsArr
	});
	
	if (callback != null && typeof callback == 'function')
		callback();
}


/**
 * shows a confirm dialog
 * @param 		string			text
 * @param 		string			header
 * @param 		function		confirmAction
 * @param 		int				height
 * @param 		int				width
 */
function showConfirmDialog(text, header, confirmAction, cancelAction, height, width, context){
	height = (height != null) ? height : 150;
	width = (width != null) ? width : 300;
	var dialogId = 'confirmDialog_' + getUniqueId();

	var buttons = [{
		text: 'OK',
		iconCls: 'icon-ok',
		handler: function(){
			$(getJqueryId(dialogId)).dialog('close');
			$(getJqueryId(dialogId)).remove();
			if (typeof confirmAction == 'function')
				confirmAction(context);
		}
	},
	{
		text: 'Abbrechen',
		iconCls: 'icon-cancel',
		handler: function(){
			$(getJqueryId(dialogId)).dialog('close');
			$(getJqueryId(dialogId)).remove();
			if (typeof cancelAction == 'function')
				cancelAction();
		}
	}
	];
	showCustomDialog(text, buttons, height, width, header, dialogId);
}


/**
 * shows the language dialog
 * @param 		int			entityId
 * @param 		string		entityName
 * @param 		function	callback
 */
function showLanguageDialog(entityId, entityName, callback){
	var params = {'T':'LANGUAGE_DIALOG', 'ID':entityId};
	params = getEncodedParams(params);

	$.ajax({
		url: pageSettings.ajaxUrl,
		dataType: 'html',
		data: params,
		type : 'get'
	}).success(function(response) {
		var id = "modalDialog_" + getUniqueId();
		var formId = '#' + entityName + '_LANGUAGE_' + entityId + '_FORM';

		var buttons = [{
			text: 'Speichern',
			iconCls: 'icon-save',
			handler: function(){
				saveAttributeLanguages(entityId, entityName, formId, getJqueryId(id), callback);
			}
		},
		{
			text: 'Abbrechen',
			iconCls: 'icon-cancel',
			handler: function(){
				$('#' + entityName + '_LANGUAGE_' + entityId + '_FORM').remove();
				$(getJqueryId(id)).dialog('close');

			}
		}
		];
		showCustomDialog(response, buttons, 200, 300, 'Sprachen festlegen', id);
	});
}


/**
 * creates an unique id based on current timestamp
 * @return		string
 */
function getUniqueId(){
	var newDate = new Date;
	return newDate.getTime();
}


/**
 * checks if obj is null or not
 * @param		mixed		objId
 * @return      bool		isNull
 */
function isNull(objId){
	// if obj is null return true
	objId = getJqueryId(objId);
	var obj = $(objId);
	var isNull = true;
	if (obj != null){
		isNull = false;
		var element = obj.get(0).tagName.toUpperCase();
		var type = ((obj.attr('type') != null) ? obj.attr('type').toUpperCase() : null);
		try{
			switch(element){
			case 'INPUT':
				switch (type){
//				case "checkbox":
//				case "radio": 
//				var isChecked = false;
//				var elements = document.getElementsByName(obj.id);
//				var i=0;
//				while (isChecked==false && i < elements.length){
//				if (elements[i++].checked)
//				isChecked = true;
//				}

//				isNull = (isChecked ? false : true);
				//break;
				case "TEXT":
				case "FILE":
				case "HIDDEN":
				case "TEXTAREA":
					isNull = (obj.val() == '' ? true : false);
					break;
				}
				break;

			case 'SELECT':
				isNull = (obj.val() == 0 ? true: false);
				break;
			}

		}
		catch (e){
			alert("<isNull>: error while validating element!");
		}
	}
	return isNull;
}



/**
 * retuns the active record id (id of current opend tab)
 * @return		int			recordId
 */
function getActiveRecordId(){
	return getSelectedTabId('mainTabbar');
}


/**
 * returns the id of the selected tab of given tabbar
 * @param tabbarId
 * @returns
 */
function getSelectedTabId(tabbarId){
	var recordId = null;
	var tab = $('#' + tabbarId).tabs('getSelected');  

	if (tab != null)
		recordId = tab.panel('options').id;    //id of selected tab

	return recordId;
}


function closeActiveTab(tabbarId){
	tabbarId = (tabbarId == null) ? 'mainTabbar' : tabbarId;
	tabbarId = getJqueryId(tabbarId);
	var tab =  $(tabbarId).tabs('getSelected');
	var tabIndex = $(tabbarId).tabs('getTabIndex', tab);  
	$(tabbarId).tabs('close', tabIndex);
}


/**
 * sets the tab with given tabIndex in given tabbar active
 * @param		int			tabIndex
 * @param		string		tabbarId
 */
function setTabActive(tabIndex, tabbarId){
	tabbarId = getJqueryId(tabbarId);
	$(tabbarId).tabs('select', tabIndex);
}


/**
 * returns encoded url param string of this form {'id':'123f'} -> 'id=123f'
 * @param               mixed           params
 * @return              string          encParams
 */
function getEncodedParams(params){
	var encParams = '';
	for(var param in params)
		encParams += param + '=' + encodeURIComponent(params[param]) + '&';
	return encParams.substring(0,encParams.length-1);
}


/**
 * loads the tab with content into mainTabbar or the given tabbar
 * @param		string		tabHeader
 * @param		int		recordId
 * @param		string		target		ajax target
 * @param		string		tabbarId	additional tabbar
 * @param		string		url		additional ajax url (standard: http://<<server>>/saleslink/<<module>>/ajax/?id=<<recordId>>&T=<<target>>	
 */
function loadRecord(tabHeader, recordId, target, tabbarId, additionalParams, callback, url, onSelectFunction) {  
	tabbarId = '#' + ((tabbarId == null) ? 'mainTabbar' : tabbarId);
	url = (url == null) ? pageSettings.ajaxUrl : url;
	var params = {'ID':recordId, 'T':target};
	params = getEncodedParams(params);
	url += '?' + params;
	if (additionalParams != null){
		additionalParams = getEncodedParams(additionalParams);
		url += '&' + additionalParams;
	}

	if (!$(tabbarId).tabs('exists', tabHeader)){
		if (onSelectFunction != null && typeof onSelectFunction == 'function')
			$(tabbarId).tabs({onSelect: onSelectFunction});
		
		$(tabbarId).tabs('add',{
			title:tabHeader,  
			href: url,  
			closable:true,
			id: recordId,
			onLoad : function(){
				if (callback != null && typeof callback == 'function')
					callback();
			}
		}); 
	} else {
		$(tabbarId).tabs('select', tabHeader);
	}
}


/**
 * saves the current record
 */
function save() {
	var recordId = getActiveRecordId();		//record id is the id of open tab
	if (recordId != null);
	saveRecord(recordId);	//must declared in each module js file
}


/**
 * saves the translation and their languages
 * @param 		int			entityId
 * @param 		string		entityName
 * @param 		string		formId
 * @param 		string		dialogId
 * @param 		function	callback
 */
function saveAttributeLanguages(entityId, entityName, formId, dialogId, callback){
	var prefix = entityName + '_LANGUAGE_' + entityId + '_';
	var formName = '#' + prefix + 'FORM';
	var params = {'T':'SAVE_LANGUAGE_VALUES', 'ID':entityId};
	params = getEncodedParams(params);
	params += '&' + $(formName).getFormParams();

	$.ajax({
		url: pageSettings.ajaxUrl,
		dataType: 'json',
		data: params,
		type : 'get',
	}).success(function(response) {
		interpretResponse(response, prefix);
		if (response.STATUS == pageSettings.success){
			callback(formId, dialogId);
		}
	});
}



/**
 * returns the text from the searchbox
 * @returns			string
 */
function getFilterText(id){
	id = (id != null) ? getJqueryId(id) : 'input.searchbox-text';
	var filterText = $(id).val();
	filterText = (filterText == 'suchen...') ? '' : filterText;
	return filterText;
}


/**
 * loads the model info and calls the callback function
 * @param 		int			entityId
 * @param 		string		entityType
 * @param 		function	callback
 */
function getModelInfo(entityId, entityType, callback, sync, additionalParams){
	var params = {'T':'MODEL_INFO', 'ID':entityId, 'ENTITY':entityType};
	params = getEncodedParams(params);
	params = (additionalParams != null) ? combineParams(params, getEncodedParams(additionalParams)) : params;
	sync = (sync == null) ? false : sync;

	$.ajax({
		url: pageSettings.ajaxUrl,
		dataType: 'json',
		data: params,
		type : 'get',
		async : sync
	}).success(function(response) {
		if (typeof callback == 'function')
			callback(response);
	});
}


/**
 * formats a date in this format yyyy-mm-dd
 * @param 		date	date
 * @returns		string
 */
function formatDate(date){
	var y = date.getFullYear();  
	var m = date.getMonth() + 1;  
	var d = date.getDate();  
	return y + '-' + (m < 10 ? ('0' + m) : m) + '-' + (d < 10 ? ('0' + d) : d);    
}


/**
 * returns the text from a datebox
 * @param 		string		id
 * @param 		boolean		encode
 * @return		string
 */
function getDateText(id, encode){
	id = getJqueryId(id);
	var text = $(id).next().find('input').val();
	if (encode)
		return encodeURIComponent(text);
	return text;
}


/**
 * combines the params
 * if the last char is not a &, inserts it, else combine it only
 * @param 		string		params
 * @param 		string		toCombineParams
 * @returns		string
 */
function combineParams(params, toCombineParams){
	if (params[params.length -1] == '&')
		params += toCombineParams;
	else
		params += '&' + toCombineParams;
	return params;
}


/**
 * generates a random string
 * @param 		int			length
 * @param 		string		charSet
 * @returns		string
 */
function getRandomText(length, charSet){
	length = (length != null) ? length : 10;
	charSet = (charSet != null) ? charSet : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    var randomString = '';
    for (var i = 0; i <= length; i++) {
    	var randomPoz = Math.floor(Math.random() * charSet.length);
    	randomString += charSet.substring(randomPoz,randomPoz+1);
    }
    return randomString;
}


/**
 * handles filtering the grid
 */
function handleFilter(){
	var filterValue = getFilterText();
	var jsonInfo = getCheckedJsonInfo('filtertree');
	var params = {'T':'FILTER_GRID', 'FILTER':filterValue, 'GRID':'MAIN', 'CHECKED_TREE_ITEMS':jsonInfo};
	reloadGrid('mainGrid', params);
}
